if( !window.console ) {
	window.console = {};
	window.console.log   = function(o){ alert(o); };
	window.console.info  = function(o){ alert(o); };
	window.console.dir   = function(o){ alert(o); };
	window.console.error = function(o){ alert(o); };
}

(function() {
   jQuery.fn['bounds'] = function () {
     var bounds = {left: Number.POSITIVE_INFINITY, top: Number.POSITIVE_INFINITY,
                   right: Number.NEGATIVE_INFINITY, bottom: Number.NEGATIVE_INFINITY};

     this.each(function (i,el) {
                 var elQ = $(el);

                 if (elQ.length == 0)
                   return;

                 var off = elQ.offset();
                 off.right = off.left + $(elQ).width();
                 off.bottom = off.top + $(elQ).height();

                 if (off.left < bounds.left)
                   bounds.left = off.left;

                 if (off.top < bounds.top)
                   bounds.top = off.top;

                 if (off.right > bounds.right)
                   bounds.right = off.right;

                 if (off.bottom > bounds.bottom)
                   bounds.bottom = off.bottom;

               });
     bounds.width = bounds.right - bounds.left;
     bounds.height = bounds.bottom - bounds.top;
     return bounds;
   }
})();

var form2json = function( elem ) {
	var inputs = $('#' +  elem + ' :input');
	
	var params = {};
	for( var i = 0, len = inputs.length; i < len; i++ ) {
		params[$( inputs[i] ).attr('name')] = $( inputs[i] ).val();
	}

	return params;
};

var editCode = function( ob ) {
	$.post(
			$( ob ).attr( 'href' ), 
			null,
			function( resp ){
				var used = $( ob ).parent().parent().find( 'td.used' );
				if( !resp.oper ) {
					$( ob ).attr( 'href', $( ob ).attr( 'href' ).replace( 'oper/0', 'oper/1' ) );
					$( ob ).empty().text( 'Oznacz jako wolny' );
					used.empty().text( 'tak' );
				} else {
					$( ob ).attr( 'href', $( ob ).attr( 'href' ).replace( 'oper/1', 'oper/0' ) );
					$( ob ).empty().text( 'Oznacz jako użyty' );
					used.empty().text( 'nie' );
				}

				used.effect("highlight", { color: 'green' }, 1000);
				$( ob ).effect("highlight", { color: 'green' }, 1000);
			},
			'json'
		);
	return false;
};

var editProduct = function() {
	$(document).ready(function(){
		var reqText  = /^[a-zA-Z0-9\-\_\ ]{1,30}$/;
		
		var dimension = $( '#dimension' );
		var dform = $('#dform');
		var dlist = $('#dlist');
		
		var editAction = function( ob ) {
		var elem = $( ob ).parent().parent();
		var bounds = elem.bounds();
			
		var progressbar = $( '<div></div>' );
		progressbar.css({ 
			position: 'absolute',
			top: bounds.top + 'px',
			left: bounds.left + 'px',
			width: parseInt( bounds.right - bounds.left ) + 'px',
			height: parseInt( bounds.bottom - bounds.top ) + 'px'
		});
		$( 'body' ).append( progressbar);
			
		var i = 0;
		var rIntv = window.setInterval(function() {
			i++;
			
			progressbar.progressbar({
				value: i
			});
			
			if( i >= 100 ) {
				window.clearInterval( rIntv );
			}
		}, 10 );

		$.post(
			$( ob ).attr( 'href' ),
			null,
			function( resp ){
				progressbar.css({ display: 'none' });
				window.clearInterval( rIntv );
				$(window).scrollTop( dform.bounds().top );
				
				var inputs = $('#formitem :input');
				var el;
				for( var i = 0, len = inputs.length; i < len; i++ ) {
					el = $( inputs[i] );
					el.val( resp.data[el.attr( 'name' )] );
				}
			},
			'json'
		);
	}
		
		dlist.find('a.edit').click(function(){
			editAction( this );
			return false;
		});
		
		var deleteAction = function( ob ) {
			var answer = confirm("Usunąć wybrany rekord?");
			if (answer){
				$( ob ).parent().parent().effect("highlight", {
					color: 'red'
				}, 1000, function(){
					$( this ).remove();
				});

				$.post(
					$( ob ).attr( 'href' ),
					null,
					function( resp ){
					},
					'json'
				);
			}
			return false;
		};
		
		dlist.find('a.delete').click(function(){
			deleteAction( this );
			return false;
		});

		dimension.click(function(){
			var fieldName = dform.find( 'input[name="name"]' );
			if( !reqText.test( fieldName.val() ) ) {
				alert( 'Musisz podać przynajmniej nazwe wymiaru, dozowolne znaki: a-zA-Z0-9_' );
				return;
			}
			
			dform.animate({
				opacity: 0
			});

			var params = form2json( 'formitem' );

			$.post(
				baseUrl + '/cpproducts/savedimension',
				params,
				function( resp ){
					dform.animate({
						opacity: 1
					});
					
					var inputs = $('#formitem :input');
					var el;
					for( var i = 0, len = inputs.length; i < len; i++ ) {
						el = $( inputs[i] );
						if( el.attr( 'name' ) != 'products_p_id' ) {
							el.val( null );
						}
					}

					if( resp.edit ) {
						var tr = $( '#tr_' + resp.id );
						tr.find( 'td' )[0].innerHTML = resp.name;
						$(window).scrollTop( parseInt( tr.bounds().top - 30 ) );
						tr.effect("highlight", {
							color: 'green'
						}, 2000 );
						
						return;
					}
					dlist.find( '#emptydlist' ).remove();
					dlist.append( 
						'<tr id="tr_' + resp.id + '">' +
							'<td>' + params.name + '</td>' +
							'<td>' +
								'<a class="edit" href="' + baseUrl + '/cpproducts/editdimension/id/' + resp.id + '">Edytuj</a>' +
								'<a class="delete" href="' + baseUrl + '/cpproducts/deletedimension/id/' + resp.id + '">Usuń</a>' +
							'</td>' +
						'</tr>'
					);
					
					$( '#tr_' + resp.id ).find('a.edit').click(function(){
						editAction( this );
						return false;
					});

					$( '#tr_' + resp.id ).find('a.delete').click(function(){
						deleteAction( this );
						return false;
					});					
				},
				'json'
			);

		});
	});
};

/**
 * link products
 */
var linkAction = function( ob, special ) {
	var size = $( '#listabg' ).bounds();
	var special = special || 0;
	
	$('#bgbgbg').css({
		position: 'absolute',
		top: '0px',
		left: '0px',
		width: size.width + 'px',
		height: size.height + 'px',
		background: '#fff',
		opacity: 0
	}).animate({
		opacity: 0.9
	});
	
	$.post(
		$( ob ).attr( 'href' ),
		{
			id : productsId,
			special : special
		},
		function( resp ) {
			$( "#lettercontent" ) .empty().append( resp );
			linkProduct(special);
			if( linkProductArray.length ) {
				
				var list = $( 'label.linkproducts input' );
				for( var i = 0, len = list.length; i < len; i++ ) {
					for( var a = 0, len2 = linkProductArray.length; a < len2; a++ ) {
						if( linkProductArray[a] == $( list[i] ).val() ) {
							$( list[i] ).attr({ checked: true });
						}
					}
				}
			}
		}
	);
};

var linkProductArray = [];
var linkProduct = function( special ) {
	$( '#letter' ).find( 'a' ).click(function(){
		linkAction( this, special );
		return false;
	});
	
	var special = special || 0;

	$( 'label.linkproducts input' ).click(function(){
		if( $( this ).is(':checked') ) {
			linkProductArray.push( $( this ).val() );
			
			$.post(
				baseUrl + '/cpproducts/linkproducts/id/' + $( this ).val() + '/p_id/' + productsId,
				{
					oper : 'add',
					special : special
				},
				function( resp ) {
				},
				'json'
			);
			
		} else {
			var val = $( this ).val();
			var tempArr = [];
			for( var i = 0, len = linkProductArray.length; i < len; i++ ) {
				if( linkProductArray[i] != val ) {
					tempArr.push( linkProductArray[i] );
				} else {
					$.post(
						baseUrl + '/cpproducts/linkproducts/id/' + $( this ).val() + '/p_id/' + productsId,
						{
							oper : 'del',
							special : special
						},
						function( resp ) {
						},
						'json'
					);
				}
			}
			
			linkProductArray = [];
			linkProductArray = tempArr;
		}
	});
	
	$( '#pagerajax' ).find( 'a' ).click(function(){
		linkAction( this );
		return false;
	});
};

var tabs;

var confirmDelete = function() {
	var answer = confirm("Usunąć wybrany rekord?");
	if (answer){
		return true;
	} else {
		return false;
	}
};

$(document).ready(function(){
	if( !logged ) {
		window.setTimeout(function(){

			var settings = {
				tl: { radius: 10 },
				tr: { radius: 10 },
				bl: { radius: 10 },
				br: { radius: 10 },
				antiAlias: true,
				autoPad: true
			};
	
			$('.login-form form').corner(settings).attr({ id : 'loginform' });
			
			settings = {
					tl: { radius: 2 },
					tr: { radius: 2 },
					bl: { radius: 2 },
					br: { radius: 2 }
				};
			$('.login-form form p.submit a.button').corner(settings).attr({ id : 'submit' });
			$('.login-form').css({
				display: 'block',
				opacity: 0
			}).animate({
				opacity: 1
			});

			$('a#submit').click(function(){
				$('#loginform').submit();
			});
		},100);
	} else {
		var instance;

		var settings = {
			tl: { radius: 2 },
			tr: { radius: 2 },
			bl: { radius: 2 },
			br: { radius: 2 }
		};
		window.setTimeout(function(){
			$('a.button').corner(settings);
		}, 200 );

		var opercomm = $('.opercomm');
		opercomm.corner(settings).attr({ id : 'operout' });
		window.setTimeout( function(){
			
			$( '#operout' ).parent().animate({
				height: '0px',
				marginTop: '0px',
				paddingTop: '0px',
				marginBottom: '0px',
				paddingBottom: '0px',
				opacity: 0
			}, 1000, null, function(){
				$(this).css({ display: 'none' });
			});
			
		}, 5000 );
		
		var player = $( '<div></div>' );
		player.css({
			display: 'none',
			width: '200px',
			height: '200px',
			position: 'absolute',
			top: '0px',
			left: '0px'
		}).hover(function(){
			$(this).css({ display: 'block' });
			instance.attr( 'class', ( instance.attr( 'class' ) == 'act' ) ? 'act' : 'hv' );
		}, function(){
			$(this).css({ display: 'none' });
			instance.attr( 'class', ( instance.attr( 'class' ) == 'act' ) ? 'act' : null );
		});
		
		$(document.body).append( player );

		
		var menu = $( 'ul.menu li' );
		menu.hover(function(){
			instance = $(this);
			
			var spans = instance.find( 'div' );
			if( spans.length ) {
				
				var color = {
					background : ( instance.attr( 'class' ) == 'act' ) ? '#cacaca' : '#EFEFEF',
					border : ( instance.attr( 'class' ) == 'act' ) ? '#999' : '#DFDFDF',
					className : ( instance.attr( 'class' ) == 'act' ) ? 'act' : 'hv'
				};
				
				var cl = ( color.className == 'act' ) ? 'act' : null;
				
				var bounds = instance.bounds();
				
				var elHeight = 28;
				instance.attr( 'class', color.className );
				player.css({
					top: parseInt( bounds.top + elHeight ) + 'px',
					left: bounds.left + 'px',
					background: color.background,
					borderLeft: '6px solid ' + color.border,
					display: 'block',
					height: parseInt( 30 * spans.length ) + 'px'
				})
				player.empty();
				for( var i = 0, len = spans.length; i < len; i++ ) {
					player.append( $( spans[i] ).clone().css({ display: 'block' }) );
				}
				
			}
		},function(){
			instance = $( this );
			var cl = ( instance.attr( 'class' ) == 'act' ) ? 'act' : null;
			player.css({ display: 'none' });	
			instance.attr( 'class', cl );
		});
	}
});